package com.itboye.ihomebank.me;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera.Area;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.adapter.ChengShiAdapter;
import com.itboye.ihomebank.adapter.ChooseAreaAdapter;
import com.itboye.ihomebank.adapter.QuAdapter;
import com.itboye.ihomebank.adapter.QuBean;
import com.itboye.ihomebank.adapter.QuYuAdapter;
import com.itboye.ihomebank.adapter.XiaoQuYuAdapter;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.AvatarDataBeans;
import com.itboye.ihomebank.bean.QuYuBean;
import com.itboye.ihomebank.bean.QuYuBean.Children;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.CityChildrenWheelAdapter;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.CityWheelAdapter;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.XiaoQuChildWheelAdapter;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.XiaoQuFatherWheelAdapter;
import com.itboye.ihomebank.home.ActivityHomeSouSuo;
import com.itboye.ihomebank.photo.Bimp;
import com.itboye.ihomebank.photo.FileUtils;
import com.itboye.ihomebank.photo.PhotoActivity;
import com.itboye.ihomebank.photo.TestPicActivity;
import com.itboye.ihomebank.presenter.HousePresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.ChengShiPopupWindow;
import com.itboye.ihomebank.util.HuXingPopupWindow;
import com.itboye.ihomebank.util.UploadImage;
import com.itboye.ihomebank.util.UploadImage.OnUploadlistener;
import com.itboye.ihomebank.util.XImageLoader;
import com.itboye.ihomebank.util.XiaoQuPopupWindow;
import com.itboye.ihomebank.wheelview.OnWheelScrollListener;
import com.itboye.ihomebank.wheelview.WheelView;
import com.itboye.ihomebank.wheelview.adapter.NumericWheelAdapter;

/**
 * 
 * 发布房源（1）
 * 
 */
public class ActivityFaBuHouse extends BaseOtherActivity implements Observer,
		OnUploadlistener {
	ImageView fabu_house_close;
	private ImageView fabu_house_img;// 大图
	private LinearLayout fabu_house_imgs;
	private ImageView fabu_house_add;// 添加图片
	private TextView fabu_house_ok;// 下一步
	private TextView fabu_house_fangshi;
	private EditText fabu_house_title, fabu_house_phone, fabu_house_people;

	private GridView noScrollgridview;
	private GridAdapter adapter;

	RelativeLayout re_choose_city;// 选择市区
	TextView tv_city, tv_area;// 显示市区和小区
	RelativeLayout re_choose_xiaoqu;// 小区

	List<String> list = new ArrayList<String>();

	PopupWindow mPopWin;
	ChengShiAdapter chengShiAdapter;

	List<QuYuBean> chengShiBean;// 城市

	// 获取市的各个区
	HousePresenter hourse;
	QuYuAdapter quYuAdapter;
	List<QuYuBean.Children> chengShiChildrenbean;

	/** 弹出框在这个布局的下面 */
	RelativeLayout fabu_main;

	private LinearLayout layout;
	/** 区 */
	ListView cheng_listView;
	/** 区域(各个区域下面的分支) */
	ListView qu_listView;
	/** 区域显示部分 */
	FrameLayout chengqu_layout;

	// 获取市的各个区下面的分支
	HousePresenter hourse02;
	QuAdapter quAdapter;
	List<QuBean> quBean;
	/** 小区 */
	List<QuBean.Children> quBeanChildren;

	XiaoQuYuAdapter xiaoQuYuAdapter;

	/** 城市名字 */
	private String chengName;
	/** 区的code */
	private String quCode;

	/** 小区的code */
	private String xiaoquCode;

	private String QuName;

	List<String> listPicture = new ArrayList<String>();

	ArrayList<AvatarDataBeans> resultData;
	private ChengShiPopupWindow chengshiPop;
	private XiaoQuPopupWindow xiaoquPop;
	private WheelView chengshiFather;
	private WheelView chengshiChild;
	private CityChildrenWheelAdapter cityChildAdpter;
	private CityWheelAdapter nume01;
	private XiaoQuFatherWheelAdapter xiaoquFatherAdapter;
	private XiaoQuChildWheelAdapter xiaoquChildAdapter;
	private WheelView xiaoquFather;
	private WheelView xiaoquChild;

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.fabu_house_close:
			finish();
			break;
		case R.id.fabu_house_ok:

			for (int i = 0; i < Bimp.drr.size(); i++) {
				String Str = Bimp.drr.get(i).substring(
						Bimp.drr.get(i).lastIndexOf("/") + 1,
						Bimp.drr.get(i).lastIndexOf("."));
				list.add(FileUtils.SDPATH + Str + ".JPEG");
			}
			int size = list.size();
			if (size <= 0) {
				ByAlert.alert("请上传相关房源图片");
				return;
			}
			String[] arr = (String[]) list.toArray(new String[size]);
			// UploadImage.getInstance().execute(arr,"house", this, null);
			String title = fabu_house_title.getText().toString();
			String phone = fabu_house_phone.getText().toString();
			String people = fabu_house_people.getText().toString();
			if (title.equals("")) {
				ByAlert.alert("请输入标题");
				return;
			}
			if (xiaoquCode == null) {
				ByAlert.alert("请选择小区");
				return;
			}
			if (phone.equals("")) {
				ByAlert.alert("请输入联系电话");
				return;
			}
			if (people.equals("")) {
				ByAlert.alert("请输入联系人");
				return;
			}

			intent = new Intent(this, ActivityFaBuHouseTwo.class);
			Bundle bundle = new Bundle();
			bundle.putString("title", title);
			if (size > 0)
				bundle.putSerializable("path", arr);

			bundle.putString("xiaoquCode", xiaoquCode);

			bundle.putString("phone", phone);
			bundle.putString("people", people);
			intent.putExtras(bundle);
			startActivity(intent);

			break;
		case R.id.re_choose_city:// 选择市区
			chengShi();
			chengshiPop.showAtLocation(v, Gravity.BOTTOM
					| Gravity.CENTER_HORIZONTAL, 0, 0);
			// chengquWindow(v);

			break;
		case R.id.re_choose_xiaoqu:// 小区
			if (quBean != null) {
				xiaoqu();
				xiaoquPop.showAtLocation(v, Gravity.BOTTOM
						| Gravity.CENTER_HORIZONTAL, 0, 0);
			} else {
				ByAlert.alert("请先选择城市地区");
			}
			// xiqoquWindow(v);
			break;
		case R.id.huxing_cancel:
			chengshiPop.dismiss();
			break;
		case R.id.huxing_ok:
			QuYuBean quYuBean = null;
			Children children = null;
			try {
				quYuBean = nume01.getPosition(chengshiFather.getCurrentItem());
				children = cityChildAdpter.getChildPoisition(chengshiChild
						.getCurrentItem());
			} catch (Exception e) {
				// TODO: handle exception
			}

			quCode = (children == null ? quYuBean.getCode() : children
					.getCode());
			hourse02 = new HousePresenter(ActivityFaBuHouse.this);
			hourse02.getQuyuLieBiao02(quCode);

			tv_city.setText(quYuBean.getName() + "  " + children == null ? ""
					: children.getName());
			chengshiPop.dismiss();
			break;
		default:
			break;
		}
	}

	/**
	 * 弹出框
	 */
	private void chengShi() {
		// 户型
		chengshiPop = new ChengShiPopupWindow(this, this, "市区选择");
		chengshiFather = (WheelView) chengshiPop.getContentView().findViewById(
				R.id.huxing_01);
		chengshiFather.setBackgroundResource(R.drawable.white);
		System.out.println(chengShiBean.size() + "城市条目");
		nume01 = new CityWheelAdapter(MyApplcation.ctx, 1, chengShiBean.size());
		nume01.setLabel("室");
		nume01.setDatas(chengShiBean);
		// NumericWheelAdapter nume02 = new
		// NumericWheelAdapter(MyApplcation.ctx,
		// 1, chengShiBean.size());
		chengshiFather.setViewAdapter(nume01);
		chengshiFather.setCyclic(false);// 是否可循环滑动
		chengshiFather.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				setCityChildenData(wheel.getCurrentItem());
				// wheel.getCurrentItem();
			}
		});

		chengshiChild = (WheelView) chengshiPop.getContentView().findViewById(
				R.id.huxing_02);
		chengshiChild.setBackgroundResource(R.drawable.white);
		setCityChildenData(0);
	}

	/**
	 * 弹出框
	 */
	private void xiaoqu() {
		// 选择小区
		xiaoquPop = new XiaoQuPopupWindow(this, xiaoquClickLisenter, "小区选择");
		xiaoquFather = (WheelView) xiaoquPop.getContentView().findViewById(
				R.id.huxing_01);
		xiaoquFather.setBackgroundResource(R.drawable.white);
		System.out.println(quBean.size() + "小区父类条目");
		xiaoquFatherAdapter = new XiaoQuFatherWheelAdapter(MyApplcation.ctx, 1,
				quBean.size());
		xiaoquFatherAdapter.setDatas(quBean);
		xiaoquFather.setViewAdapter(xiaoquFatherAdapter);
		// xiaoquFather.setVisibleItems(3);
		xiaoquFather.setCyclic(false);// 是否可循环滑动
		xiaoquFather.addScrollingListener(new OnWheelScrollListener() {

			@Override
			public void onScrollingStarted(WheelView wheel) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScrollingFinished(WheelView wheel) {
				// TODO Auto-generated method stub
				setXiaoQuChildenData(wheel.getCurrentItem());
				// wheel.getCurrentItem();
			}
		});

		xiaoquChild = (WheelView) xiaoquPop.getContentView().findViewById(
				R.id.huxing_02);
		xiaoquChild.setBackgroundResource(R.drawable.white);
		setXiaoQuChildenData(0);
	}

	OnClickListener xiaoquClickLisenter = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.huxing_cancel:
				break;
			case R.id.huxing_ok:
				QuBean xiaoquFatherBean = xiaoquFatherAdapter
						.getPosition(xiaoquFather.getCurrentItem());
				com.itboye.ihomebank.adapter.QuBean.Children children = null;
				try {
					children = xiaoquChildAdapter.getPosition(xiaoquChild
							.getCurrentItem());
				} catch (Exception e) {
					// TODO: handle exception
				}
				tv_area.setText(xiaoquFatherBean.getName() + "  "
						+ (children == null ? "" : children.getName()));
				xiaoquCode = (children == null ? xiaoquFatherBean.getCode()
						: children.getCode());
				break;
			default:
				break;
			}

			xiaoquPop.dismiss();
		}
	};

	void setCityChildenData(int index) {
		if (chengShiBean != null) {
			if (chengShiBean.size() > 0) {
				if (chengShiBean.get(index).getChildren().size() > 0) {
					cityChildAdpter = new CityChildrenWheelAdapter(
							MyApplcation.ctx, 1, chengShiBean.get(index)
									.getChildren().size());
					// nume03.setLabel("厅");
					cityChildAdpter.setDatas(chengShiBean.get(index)
							.getChildren());
					chengshiChild.setViewAdapter(cityChildAdpter);
					chengshiChild.setCyclic(false);// 是否可循环滑动
					chengshiChild
							.addScrollingListener(new OnWheelScrollListener() {

								@Override
								public void onScrollingStarted(WheelView wheel) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onScrollingFinished(WheelView wheel) {
									// TODO Auto-generated method stub

								}
							});
				}
			}
		}
	}

	void setXiaoQuChildenData(int index) {
		if (quBean != null) {
			if (quBean.size() > 0) {
				if (quBean.get(index).getChildren().size() > 0) {
					xiaoquChildAdapter = new XiaoQuChildWheelAdapter(
							MyApplcation.ctx, 1, quBean.get(index)
									.getChildren().size());
					// nume03.setLabel("厅");
					xiaoquChildAdapter
							.setDatas(quBean.get(index).getChildren());
					xiaoquChild.setViewAdapter(xiaoquChildAdapter);
					xiaoquChild.setCyclic(false);// 是否可循环滑动
					xiaoquChild
							.addScrollingListener(new OnWheelScrollListener() {

								@Override
								public void onScrollingStarted(WheelView wheel) {
									// TODO Auto-generated method stub

								}

								@Override
								public void onScrollingFinished(WheelView wheel) {
									// TODO Auto-generated method stub

								}
							});
				} else {
					xiaoquChildAdapter = new XiaoQuChildWheelAdapter(
							MyApplcation.ctx, 0, 0);
					xiaoquChildAdapter.notifyDataSetChanged();
					xiaoquChild.setViewAdapter(xiaoquChildAdapter);
				}
			} else {
				xiaoquChildAdapter = new XiaoQuChildWheelAdapter(
						MyApplcation.ctx, 0, 0);
				xiaoquChildAdapter.notifyDataSetChanged();
				xiaoquChild.setViewAdapter(xiaoquChildAdapter);
			}
		} else {
			xiaoquChildAdapter.notifyDataSetChanged();
			xiaoquChild.setViewAdapter(xiaoquChildAdapter);
		}
	}

	@Override
	protected int layout_id() {
		return R.layout.activity_fabu_house;
	}

	@Override
	protected void onInitController() {
		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);

		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.bmp.size()) {
					new PopupWindows(ActivityFaBuHouse.this, noScrollgridview);
				} else {
					Intent intent = new Intent(ActivityFaBuHouse.this,
							PhotoActivity.class);
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

	}

	TextView fabu_house_v;

	@Override
	protected void onInit() {
		hourse = new HousePresenter(this);
		hourse.getQuyuLieBiao("");
		fabu_house_v.setVisibility(View.GONE);
	}

	@Override
	protected void onReadIntent(Bundle bundle) {

	}

	private static final int TAKE_PICTURE = 0x000000;
	private String path = "";

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File file = new File(Environment.getExternalStorageDirectory()
				+ "/myimage/", String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		path = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.drr.size() < 9 && resultCode == -1) {
				Bimp.drr.add(path);
			}
			break;
		}
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	public class PopupWindows extends PopupWindow {

		public PopupWindows(Context mContext, View parent) {

			View view = View
					.inflate(mContext, R.layout.item_popupwindows, null);
			view.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.fade_ins));
			LinearLayout ll_popup = (LinearLayout) view
					.findViewById(R.id.ll_popup);
			ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
					R.anim.push_bottom_in_2));

			setWidth(LayoutParams.FILL_PARENT);
			setHeight(LayoutParams.FILL_PARENT);
			setBackgroundDrawable(new BitmapDrawable());
			setFocusable(true);
			setOutsideTouchable(true);
			setContentView(view);
			showAtLocation(parent, Gravity.BOTTOM, 0, 0);
			update();

			Button bt1 = (Button) view
					.findViewById(R.id.item_popupwindows_camera);
			Button bt2 = (Button) view
					.findViewById(R.id.item_popupwindows_Photo);
			Button bt3 = (Button) view
					.findViewById(R.id.item_popupwindows_cancel);
			bt1.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					photo();
					dismiss();
				}
			});
			bt2.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(ActivityFaBuHouse.this,
							TestPicActivity.class);
					startActivity(intent);
					dismiss();
				}
			});
			bt3.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					dismiss();
				}
			});

		}
	}

	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater; // 视图容器
		private int selectedPosition = -1;// 选中的位置
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			return (Bimp.bmp.size() + 1);
		}

		public Object getItem(int arg0) {

			return null;
		}

		public long getItemId(int arg0) {

			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		/**
		 * ListView Item设置
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			final int coord = position;
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.bmp.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (Bimp.bmp.size() > 0)
					fabu_house_img.setImageBitmap(Bimp.bmp.get(position - 1));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.bmp.get(position));
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.drr.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							try {
								String path = Bimp.drr.get(Bimp.max);
								System.out.println(path);
								Bitmap bm = Bimp.revitionImageSize(path);
								Bimp.bmp.add(bm);
								String newStr = path.substring(
										path.lastIndexOf("/") + 1,
										path.lastIndexOf("."));
								FileUtils.saveBitmap(bm, "" + newStr);
								Bimp.max += 1;
								Message message = new Message();
								message.what = 1;
								handler.sendMessage(message);
							} catch (IOException e) {

								e.printStackTrace();
							}
						}
					}
				}
			}).start();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observable, Object data) {
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == HousePresenter.quyuLieBiao_success) {
				chengShiBean = (List<QuYuBean>) entity.getData();

				chengShiChildrenbean = new ArrayList<QuYuBean.Children>();

				for (int i = 0; i < chengShiBean.size(); i++) {
					chengShiChildrenbean.addAll(chengShiBean.get(i)
							.getChildren());// 得到市下面的区
				}
			}
			if (entity.getEventType() == HousePresenter.quyuLieBiao_fail) {
				ByAlert.alert(chengShiChildrenbean.toString());
			}

			if (entity.getEventType() == HousePresenter.quyuLieBiao02_success) {
				quBean = (List<QuBean>) entity.getData();

				quBeanChildren = new ArrayList<QuBean.Children>();

				for (int i = 0; i < quBean.size(); i++) {
					quBeanChildren.addAll(quBean.get(i).getChildren());// 得到区域下面的小区
				}
			}

			if (entity.getEventType() == HousePresenter.quyuLieBiao02_fail) {
				ByAlert.alert(entity.getData());
			}
		}
	}

	@Override
	public void OnSuccess(ArrayList<AvatarDataBeans> resultData) {

		AvatarDataBeans bean = new AvatarDataBeans();
		for (int i = 0; i < resultData.size(); i++) {
			bean.setId(resultData.get(i).getId());

			listPicture.add(resultData.get(i).getId());
		}
	}

	@Override
	public void OnError(String resultData) {
		ByAlert.alert("上传失败");

	}

}
